from pymongo import MongoClient
from scrapy.exceptions import DropItem

class YueshushuPipeline:
    def __init__(self, mongo_uri, mongo_db, collection_name, mongo_port=27017):
        self.mongo_uri = mongo_uri
        self.mongo_db = mongo_db
        self.collection_name = collection_name
        self.mongo_port = mongo_port
        self.client = None
        self.db = None

    @classmethod
    def from_crawler(cls, crawler):
        return cls(
            mongo_uri=crawler.settings.get('MONGODB_SERVER'),
            mongo_db=crawler.settings.get('MONGODB_DB'),
            collection_name=crawler.settings.get('MONGODB_COLLECTION'),
            mongo_port=crawler.settings.get('MONGODB_PORT', 27017)
        )

    def open_spider(self, spider):
        self.client = MongoClient(self.mongo_uri, self.mongo_port)
        self.db = self.client[self.mongo_db]

    def close_spider(self, spider):
        self.client.close()

    def process_item(self, item, spider):
        self.db[self.collection_name].insert_one(dict(item))
        print(f'插入数据 {item} 成功')
        return item